package com.action;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conf.Parameters;
import com.conf.User;


public class AbstractServlet extends HttpServlet {


	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
		doAction(req,res);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
		doAction(req,res);
	}

	public void doAction(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
		Collection actionsAllowed;
		User user = (User) req.getSession().getAttribute(Parameters.USER_ATTRIBUTE);
		if (user != null) {
			actionsAllowed = user.getActionsAllowed();
			if (actionsAllowed == null) {
				actionsAllowed = new ArrayList();
				actionsAllowed.add("Login");
			}
		} else {
			actionsAllowed = new ArrayList();
			actionsAllowed.add("Login");
		}
		String action = getClassName(req);
		if(actionAllowed(action,actionsAllowed)){
			try {
				Class c=Class.forName(action);
				AbstractAction actionToDo=(AbstractAction)c.newInstance();
				String redirect=actionToDo.doAction(req,res);
				if(redirect!=""){
					String basePath=req.getContextPath();
					res.sendRedirect(basePath+redirect);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			
		}
	}
	
	private boolean actionAllowed(String action,Collection actions){
		Iterator it=actions.iterator();
		while(it.hasNext()){
			if(("com.action."+it.next().toString()).equals(action)){
				return true;
			}
		}
		return false;
	}
	
	private String getClassName(HttpServletRequest req){
		String cls=req.getParameter("doAction");
		return ("com.action."+cls);
	}

}
